package org.skydiveapphd;

import java.util.ArrayList;
import java.util.List;

import org.skydiveapphd.interfaces.RigNotifier;
import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.repository.RigRepository;
import org.skydiveapplibrary.ui.GearListSelectAdapter;

import android.os.Bundle;
import android.widget.ListView;

public class GearListSelectActivity extends BaseListFragment
{

	public static GearListSelectActivity newInstance(Bundle args) 
	{
		GearListSelectActivity f = new GearListSelectActivity();
		f.setArguments(args);
		return f;
	}
	
    @Override 
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
		// init view
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		setHeaderText(R.string.gear_list_select_label);
    	
    	loadData();
    	
    	setTopButtonImage(R.drawable.ic_menu_add);
    	setBottomButtonImage(R.drawable.ic_menu_revert);
    }
    
	@Override
	protected void onTopButtonClick()
	{
		FragmentHelper.getInstance().openFragment(RigEditActivity.newInstance(new Bundle()), android.R.id.tabhost, 
				Constants.TAG_RIG_EDIT, getFragmentManager());
	}
	
	@Override
	protected void onBottomButtonClick()
	{
		// get current selection	
		RigNotifier f = (RigNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		f.updateRig(getSelectedIds());
		getFragmentManager().popBackStack();
	}

    
    @SuppressWarnings("unchecked")
	private void loadData()
    {
    	// populate list
		RigRepository repository = new RigRepository(getActivity());
		GearListSelectAdapter adapter = new GearListSelectAdapter(
				getActivity(),
				repository.getRigs());
		setListAdapter(adapter);
		
		// set initial selection
		List<Integer> selectedIdList = (List<Integer>)getArguments().getSerializable(Constants.EXTRA_SELECTED_RIG_IDS);
		
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					selectedIdList.contains(adapter.getItems().get(index).getId())); 
		}
		
    }
    
    private List<Integer> getSelectedIds()
    {
    	List<Integer> ids = new ArrayList<Integer>();
    	
    	// get adapter
    	GearListSelectAdapter adapter = (GearListSelectAdapter)getListAdapter();
    	// iterate over items
    	for (int index = 0; index < adapter.getItems().size(); index++)
		{
    		if (getListView().getCheckedItemPositions().get(index))
    		{
    			ids.add(adapter.getItems().get(index).getId());
    		}
		}
    	
    	return ids;
    }
} 